<?php
require_once dirname(__FILE__) . '/libraries/ServiceBase.php';
/**
 * Billing Service
 *
 */
class SDOServiceUnicode extends ServiceBase
{
    # 正式环境Billing WSDL URL
    const BILLING_WSDL = 'BILLING_WSDL';
    # 测试环境Billing WSDL URL
    const PRE_BILLING_WSDL = 'PRE_BILLING_WSDL';
    const ADD_APP_EXISTS_CODE = - 10208011;
    const ADD_AREA_EXISTS_CODE = - 10208023;
    protected static $errNo = array(
        - 10208001 => "serviceId is <= 0 ", 
        - 10208004 => "spId is null ", 
        - 10208007 => "name is null ", 
        - 10208008 => "name is more than 50 chars ", 
        - 10208009 => "TimeTypeId is not in(1,2,4,5) ", 
        - 10208010 => "notes is more than 200 chars ", 
        - 10208011 => "The ServiceId is Exist ", 
        - 10208012 => "add service error ", 
        - 10208013 => "serviceId is <= 0 ", 
        - 10208016 => "areaid is < 0 ", 
        - 10208019 => "name is null ", 
        - 10208020 => "name is more than 50 chars ", 
        - 10208021 => "notes is more than 200 chars ", 
        - 10208022 => "The ServiceId is not Exist ", 
        - 10208023 => "The AreaId for the ServiceId is Exist ", 
        - 10208024 => "add area error ", 
        - 10208025 => "serviceId is <= 0 ", 
        - 10208028 => "name is null ", 
        - 10208029 => "name is more than 50 chars ", 
        - 10208030 => "TimeTypeId is not in(1,2,4,5) ", 
        - 10208031 => "notes is more than 200 chars ", 
        - 10208032 => "The ServiceId is not Exist ", 
        - 10208033 => "modify service error ", 
        - 10208034 => "serviceId is <= 0 ", 
        - 10208037 => "The ServiceId is not Exist ", 
        - 10208038 => "delete service error ", 
        - 10208060 => "The serviceIs has 1 more area ", 
        - 10208039 => "serviceId is <= 0 ", 
        - 10208042 => "areaid is < 0 ", 
        - 10208045 => "name is null ", 
        - 10208046 => "name is more than 50 chars ", 
        - 10208047 => "notes is more than 200 chars ", 
        - 10208048 => "The ServiceId is not Exist ", 
        - 10208049 => "The AreaId for the ServiceId is not Exist ", 
        - 10208050 => "update area error ", 
        - 10208051 => "serviceId is <= 0 ", 
        - 10208052 => "areaid is < 0 ", 
        - 10208057 => "The ServiceId is not Exist ", 
        - 10208058 => "The AreaId for the ServiceId is not Exist ", 
        - 10208059 => "delete area error "
    );
    

    public static function syncUnicode (&$message, $appId, $spId = 1, $notes = '')
    {
    	$uncode_map = self::getUnicodeExist($message, $appId, $spId);
    	if(!is_array($uncode_map)) return false;
        require_once OPEN_LIB_PATH . '/open/models/OaAppServerModel.php';
        require_once OPEN_LIB_PATH . '/open/models/OaAppModel.php';
        require_once OPEN_LIB_PATH . '/open/models/OaCompanyModel.php';
        $companyModel = new OaCompanyModel();
        $sp = $companyModel->getCompany($spId);
        $appModel = new OaAppModel(2);
        $app = $appModel->getApp($appId);
        $appServerModel = new OaAppServerModel(2);
	    $arealist = $appServerModel->getAppAreas($appId);
	    $grouplist = $appServerModel->getAppGroups($appId);
        if($app['status'] <6)
        {
	        if(isset($uncode_map['sp']) && $uncode_map['sp'] == $spId)
	        {
	        	$res = self::sp($message, 'modify', $spId, $sp['name'], $notes);
	        	if(!$res) return false;
	        }
	        else
	        {
	        	$res = self::sp($message, 'add', $spId, $sp['name'], $notes);
	        	if(!$res) return false;
	        }
	        if(isset($uncode_map['app']) && $uncode_map['app'] == $appId)
	        {
	        	$res = self::app($message, 'modify', $spId, $appId, $app['name'], $notes);
	        	if(!$res) return false;
	        }
	        else
	        {
	        	$res = self::app($message, 'add', $spId, $appId, $app['name'], $notes);
	        	if(!$res) return false;
	        }
	        foreach($arealist as $area)
	        {
	        	$areaId = $area['area_code'];
	        	if(isset($uncode_map['area' . $areaId]))
	        	{
	        		$res = self::area($message, 'modify', $appId, $areaId, $area['name'], $notes);
	        		if(!$res) return false;
	        		$uncode_map['area' . $areaId] = 0;
	        	}
	        	else
	        	{
	        		$res = self::area($message, 'add', $appId, $areaId, $area['name'], $notes);
	        		if(!$res) return false;
	        	}
	        	$tmp_groups = $grouplist[$area['id']];
	        	if($tmp_groups && is_array($tmp_groups))
	        	{
		        	foreach($tmp_groups as $group)
		        	{
			        	$groupId = $group["group_code"];
			        	if(isset($uncode_map['group_' . $areaId . '_' . $groupId]))
			        	{
			        		$res = self::group($message, 'modify', $appId, $areaId, $groupId, $group['name'], $notes);
			        		if(!$res) return false;
			        		$uncode_map['group_' . $areaId . '_' . $groupId] = 0;
			        	}
			        	else
			        	{
			        		$res = self::group($message, 'add', $appId, $areaId, $groupId, $group['name'], $notes);
			        		if(!$res) return false;
			        	}
		        	}
	        	}

	        	if($area['status'] == 2) 
	        	{
	        		$res = self::area($message, 'delete', $appId, $areaId, $area['name'], $notes);
				    if(!$res) return false;
	        	}
	        	
	        }
	        
	        foreach($uncode_map as $k => $v)
	        {
	        	if($k != 'app' && $k != 'sp' && $v == 1)
	        	{
	        		//echo "del $k\n";
	        		//暂不删除
	        	}
	        }
        }
        else
        {
        	require_once OPEN_LIB_PATH . '/open/business-logic/OaAppServerLogic.php';
        	$serverModel = new OaAppServerLogic();
        	$changelist = $serverModel->getGSChanges($appId, 2, true);
        	if($changelist && is_array($changelist))
        	{
	        	foreach($changelist as $areachange)
	        	{
	        		$op = $areachange['op'];
		        	$area = (!empty($op) && $op != 'delete')?$areachange['new']:$areachange['old'];
/*		        	if($op == 'update' && $areachange['new']['status'] == 2 && $areachange['old']['status'] == 1)
		        	{
		        		$op = 'delete';
		        		$area = $areachange['old'];
		        	}
*/		        	$areaId = $area['area_code'];
/*		        	if($area['status'] == 2) 
		        	{
		        		if(isset($uncode_map['area' . $areaId]))
		        			$op = 'delete';
		        		else
		        			continue;
		        	}
*/	        		if($op) 
	        		{
		        		if($op == 'delete')
		        		{
				        	if(isset($uncode_map['area' . $areaId]))
				        	{
				        		$res = self::area($message, 'delete', $appId, $areaId, $area['name'], $notes);
				        		if(!$res) return false;
				        	}
			        	}
		        		else
		        		{
				        	if(isset($uncode_map['area' . $areaId]))
				        	{
				        		$res = self::area($message, 'modify', $appId, $areaId, $area['name'], $notes);
				        		if(!$res) return false;
				        	}
				        	else
				        	{
				        		$res = self::area($message, 'add', $appId, $areaId, $area['name'], $notes);
				        		if(!$res) return false;
				        	}
				        	$uncode_map['area' . $areaId] = 1;
			        	}
		        	}
		        	if($op == 'delete') continue;
		        	
		        	if($op == 'update' && $areachange['new']['status'] == 1 && $areachange['old']['status'] == 2)
		        	{
			        	$tmp_groups = $grouplist[$area['id']];
			        	foreach($tmp_groups as $group)
			        	{
				        	$groupId = $group["group_code"];
				        	if(isset($uncode_map['group_' . $areaId . '_' . $groupId]))
				        	{
				        		$res = self::group($message, 'modify', $appId, $areaId, $groupId, $group['name'], $notes);
				        		if(!$res) return false;
				        	}
				        	else
				        	{
				        		$res = self::group($message, 'add', $appId, $areaId, $groupId, $group['name'], $notes);
				        		if(!$res) return false;
				        	}
			        	}
		        	}
		        	
		        	$groupchanges = $areachange['group_changes'];
		        	if($groupchanges && is_array($groupchanges))
		        	{
			        	foreach($groupchanges as $groupchange)
			        	{
			        		$op = $groupchange['op'];
			        		if(!$op) continue;
			        		$group = ($op != 'delete')?$groupchange['new']:$groupchange['old'];
			        		$groupId = $group['group_code'];
			        		if($op == 'delete')
			        		{
					        	if(isset($uncode_map['group_' . $areaId . '_' . $groupId]))
					        	{
					        		$res = self::group($message, 'delete', $appId, $areaId, $groupId, $group['name'], $notes);
					        		if(!$res) return false;
					        	}
				        	}
			        		else
			        		{
					        	if(!isset($uncode_map['area' . $areaId]))
					        	{
					        		$res = self::area($message, 'add', $appId, $areaId, $area['name'], $notes);
					        		if(!$res) return false;
					        	}
					        	if(isset($uncode_map['group_' . $areaId . '_' . $groupId]))
					        	{
					        		$res = self::group($message, 'modify', $appId, $areaId, $groupId, $group['name'], $notes);
					        		if(!$res) return false;
					        	}
					        	else
					        	{
					        		$res = self::group($message, 'add', $appId, $areaId, $groupId, $group['name'], $notes);
					        		if(!$res) return false;
					        	}
				        	}
				        }
		        	}

		        	if($area['status'] == 2) 
		        	{
		        		$res = self::area($message, 'delete', $appId, $areaId, $area['name'], $notes);
					    if(!$res) return false;
		        	}

		        	
	        	}
        	}
        }
        return true;
	}


    public static function getUnicodeExist (&$message, $appId, $spId = 1, $notes = '')
    {
        $url = sdk_fetch_config(SDK_ENV . 'UNICODE_GET_URL') . '?operation=3';
        $param['serviceid'] = $appId;
//        $param['spid'] = $spId;
        //$param['test'] = $test;
        $urlSuffix = strtr(http_build_query($param), 
        array(
            "&amp;" => "&"
        ));
        $content = self::getRestfulContent($url . '&' . $urlSuffix, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__, SDK_LOG_PARAMS=> $urlSuffix );
        if ($content === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $url;
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }
        $result = simplexml_load_string($content);
        if (!$result) {
            return array();
        }
        $map = array();
        $splist = $result->sp;
		foreach($splist as $sp)
		{
	        if($sp)
	        {
	        	if(((string) $sp['status']) == '0' && (string) $sp['id'] == $spId)
					$map['sp'] = (string) $sp['id'];
	        	$app = $sp->service;
	        	if($app)
	        	{
	        		if(((string) $app['status']) == '0')
	        			$map['app'] = (string) $app['id'];
	        		$areas = $app->area;
	        		if($areas)
	        		{
	        			foreach($areas as $area)
	        			{
	        				$areaid = (string) $area['id'];
	        				if(((string) $area['status']) == '0')
	        					$map['area'.$areaid] = 1;
	        				$groups = $area->group;
	        				if($groups)
	        				{
	        					foreach($groups as $group)
	        					{
	        						if(((string) $group['status']) == '0')
	        							$map['group_' . $areaid . "_" . ((string) $group['id'])] = 1;
	        					}
	        				}
	        			}
	        		}
	        	}
	        }
        }	
        return $map;
    }
    
    /**
     * 编码库操作sp
     *
     * @param string $message #错误信息
     * @param int $appId      #APP ID	
     * @param string $name	  #应用名称
     * @param string $env     #环境（测试|正式）
     * @param int $timetypeid #计费类型
     * @param int $spId		  #服务商ID，默认为1，盛大
     * @param string $notes	  #notes
     * @return Boolean
     */
    public static function sp (&$message, $op, $spId, $name, $notes = '')
    {
        //echo "$op, $spId, $name\n";return true;
        $wsdl = $env === SDK_ENV_TEST ? sdk_fetch_config(SDK_ENV . self::PRE_BILLING_WSDL) : sdk_fetch_config(
        SDK_ENV . self::BILLING_WSDL);
        $params['spCode'] = $spId;
        $params['spName'] = $name;
        $params['type'] = 1;
        $params['status'] = 0;
        $params['notes'] = $notes;
        $options['soap_version'] = SOAP_1_1;
        if (isset($wsdl['options']) && $wsdl['options']) {
            $options = array_merge($options, $wsdl['options']);
        }
        $result = self::soapRequest($op."CodeSp", $params, $wsdl['wsdl'], $options, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__ , SDK_LOG_PARAMS=> json_encode($params));
        if ($result === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $wsdl['wsdl'];
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }
        $errMsg[SDK_LOG_REUTRN] = json_encode($result);
        if ($result->result !== "0") {
            $message = $result->message;
            $method = isset(self::$errNo[$result->result]) ? "warn" : "error";
            $errMsg[SDK_LOG_LOCATION] = $wsdl['wsdl'];
            self::$method($errMsg, __CLASS__);
            self::setErrNo($result->result);
            return FALSE;
        }
        self::log($errMsg, __CLASS__, true);
        return true;
    }


    /**
     * 编码库操作sp
     *
     * @param string $message #错误信息
     * @param int $appId      #APP ID	
     * @param string $name	  #应用名称
     * @param string $env     #环境（测试|正式）
     * @param int $timetypeid #计费类型
     * @param int $spId		  #服务商ID，默认为1，盛大
     * @param string $notes	  #notes
     * @return Boolean
     */
    public static function app (&$message, $op, $spId, $appId, $name, $notes = '')
    {
        //echo "$op, $spId, $appId, $name\n";return true;
        $wsdl = $env === SDK_ENV_TEST ? sdk_fetch_config(SDK_ENV . self::PRE_BILLING_WSDL) : sdk_fetch_config(
        SDK_ENV . self::BILLING_WSDL);
        $params['spCode'] = $spId;
        $params['appCode'] = $appId;
        $params['appName'] = $name;
        $params['type'] = 1;
        $params['status'] = 0;
        $params['notes'] = $notes;
        $options['soap_version'] = SOAP_1_1;
        if (isset($wsdl['options']) && $wsdl['options']) {
            $options = array_merge($options, $wsdl['options']);
        }
        $result = self::soapRequest($op."CodeApp", $params, $wsdl['wsdl'], $options, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__ , SDK_LOG_PARAMS=> json_encode($params));
        if ($result === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $wsdl['wsdl'];
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }
        $errMsg[SDK_LOG_REUTRN] = json_encode($result);
        if ($result->result !== "0") {
            $message = $result->message;
            $method = isset(self::$errNo[$result->result]) ? "warn" : "error";
            $errMsg[SDK_LOG_LOCATION] = $wsdl['wsdl'];
            self::$method($errMsg, __CLASS__);
            self::setErrNo($result->result);
            return FALSE;
        }
        self::log($errMsg, __CLASS__, true);
        return true;
    }


    /**
     * 编码库操作sp
     *
     * @param string $message #错误信息
     * @param int $appId      #APP ID	
     * @param string $name	  #应用名称
     * @param string $env     #环境（测试|正式）
     * @param int $timetypeid #计费类型
     * @param int $spId		  #服务商ID，默认为1，盛大
     * @param string $notes	  #notes
     * @return Boolean
     */
    public static function area (&$message, $op, $appId, $areaId, $name, $notes = '')
    {
        //echo "$op, $appId, $areaId, $name\n";return true;
        $wsdl = $env === SDK_ENV_TEST ? sdk_fetch_config(SDK_ENV . self::PRE_BILLING_WSDL) : sdk_fetch_config(
        SDK_ENV . self::BILLING_WSDL);
        $params['areaCode'] = $areaId;
        $params['appCode'] = $appId;
        $params['areaName'] = $name;
        $params['type'] = 1;
        $params['status'] = 0;
        $params['notes'] = $notes;
        $params['seeFlag'] = ($areaId == 0)?2:1;
        $params['regionFlag'] = 1;
        $params['virtualFlag'] = 1;
        $params['beginTime'] = '2000-01-01';
        $params['endTime'] = '2099-01-01';
        $params['showBeginTime'] = '2000-01-01';
        $params['showEndTime'] = '2099-01-01';
        
        $options['soap_version'] = SOAP_1_1;
        if (isset($wsdl['options']) && $wsdl['options']) {
            $options = array_merge($options, $wsdl['options']);
        }
        $result = self::soapRequest($op."CodeArea", $params, $wsdl['wsdl'], $options, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__ , SDK_LOG_PARAMS=> json_encode($params));
        if ($result === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $wsdl['wsdl'];
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }
        $errMsg[SDK_LOG_REUTRN] = json_encode($result);
        if ($result->result !== "0") {
            $message = $result->message;
            $method = isset(self::$errNo[$result->result]) ? "warn" : "error";
            $errMsg[SDK_LOG_LOCATION] = $wsdl['wsdl'];
            self::$method($errMsg, __CLASS__);
            self::setErrNo($result->result);
            return FALSE;
        }
        self::log($errMsg, __CLASS__, true);
        return true;
    }


    /**
     * 编码库操作sp
     *
     * @param string $message #错误信息
     * @param int $appId      #APP ID	
     * @param string $name	  #应用名称
     * @param string $env     #环境（测试|正式）
     * @param int $timetypeid #计费类型
     * @param int $spId		  #服务商ID，默认为1，盛大
     * @param string $notes	  #notes
     * @return Boolean
     */
    public static function group (&$message, $op, $appId, $areaId, $groupId, $name, $notes = '')
    {
        //echo "$op, $appId, $areaId, $groupId, $name\n";return true;
        $wsdl = $env === SDK_ENV_TEST ? sdk_fetch_config(SDK_ENV . self::PRE_BILLING_WSDL) : sdk_fetch_config(
        SDK_ENV . self::BILLING_WSDL);
        $params['groupCode'] = $groupId;
        $params['areaCode'] = $areaId;
        $params['appCode'] = $appId;
        $params['groupName'] = $name;
        $params['type'] = 1;
        $params['status'] = 0;
        $params['notes'] = $notes;
        $params['seeFlag'] = ($areaId == 0)?2:1;
        $params['virtualFlag'] = 1;
        $params['beginTime'] = '2000-01-01';
        $params['endTime'] = '2099-01-01';
        $params['showBeginTime'] = '2000-01-01';
        $params['showEndTime'] = '2099-01-01';
        
        $options['soap_version'] = SOAP_1_1;
        if (isset($wsdl['options']) && $wsdl['options']) {
            $options = array_merge($options, $wsdl['options']);
        }
        $result = self::soapRequest($op."CodeGroup", $params, $wsdl['wsdl'], $options, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__ , SDK_LOG_PARAMS=> json_encode($params));
        if ($result === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $wsdl['wsdl'];
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }
        $errMsg[SDK_LOG_REUTRN] = json_encode($result);
        if ($result->result !== "0") {
            $message = $result->message;
            $method = isset(self::$errNo[$result->result]) ? "warn" : "error";
            $errMsg[SDK_LOG_LOCATION] = $wsdl['wsdl'];
            self::$method($errMsg, __CLASS__);
            self::setErrNo($result->result);
            return FALSE;
        }
        self::log($errMsg, __CLASS__, true);
        return true;
    }


    public static function openQingSuan (&$message, $appId, $name = '', $pt = 'mobfan', $role = 'sdo_default',  $notes = '')
    {
        $url = sdk_fetch_config(SDK_ENV . 'QINGSUAN_GET_URL');
        $param['pt'] = $pt;
        $param['accountName'] = $pt;
        $param['appId'] = $appId;
        $param['appName'] = $name;
        $param['startTime'] = '2011-01-01 00:00:00';
        $param['endTime'] = '2111-01-01 00:00:00';
        $param['divideRole'] = $role;
        $param['state'] = 0;

        $urlSuffix = strtr(http_build_query($param), 
        array(
            "&amp;" => "&"
        ));
        $content = self::getRestfulContent($url . '?' . $urlSuffix, $message);
        $errMsg = array(SDK_LOG_METHOD=> __FUNCTION__, SDK_LOG_PARAMS=> $urlSuffix );
        if ($content === FALSE) {
            $errMsg[SDK_LOG_EXCEPTION] = $message;
            $errMsg[SDK_LOG_LOCATION] = $url;
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }
        $message = $content;
        $result = json_decode($content,true);
        if (!$result) {
            $errMsg[SDK_LOG_EXCEPTION] = $content;
            $errMsg[SDK_LOG_LOCATION] = $url;
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }
        if($result['Result'] != 0 && $result['Result'] != -10249004)
        {
            $errMsg[SDK_LOG_EXCEPTION] = $content;
            $errMsg[SDK_LOG_LOCATION] = $url;
            self::fatal($errMsg, __CLASS__);
            return FALSE;
        }

        $errMsg[SDK_LOG_EXCEPTION] = $content;
        $errMsg[SDK_LOG_LOCATION] = $url;
        self::log($errMsg, __CLASS__, true);
        return true;
    }



     /**
     * 自检函数
     */
    public static function selfTest ()
    {
        $sdk1 = sdk_fetch_config(SDK_ENV . self::PRE_BILLING_WSDL);
        $sdk2 = sdk_fetch_config(SDK_ENV . self::BILLING_WSDL);
        return self::curlTest(array(
            $sdk1['wsdl'], 
            $sdk2['wsdl']
        ));
    }
}
